<?php
namespace app\cls\tom;
/**
 * 功能描述：缓存集中处理
 * Class Cache
 * 实现方法
 * set($key)
 * get($key,$value,$ttl)
 * inc($key)
 * del($key)
 * getLastError()
 */
class Cache {
    private $shmCache;          //shmcache 缓存类型的实例对象
    private $cacheType;         //缓存类型
    private $lastError;         //上一次的错误信息
    private $prefix;            //缓存key前缀

    public function __construct($cacheType = "ShmCache") {
        $cacheType = strtolower($cacheType);
        $this->cacheType = $cacheType;
        $this->prefix = "";
        if ($cacheType == "shmcache") {
            $this->shmCache = new \ShmCache('/etc/libshmcache.conf', \ShmCache::SERIALIZER_IGBINARY);
        }
    }

    /**
     * 功能描述：设置key的前缀
     * @param $prefix
     */
    public function setPrefix($prefix) {
        $this->prefix = trim($prefix);
    }

    /**
     * 功能描述：设置缓存
     * @param $key
     * @param $value
     * @param $ttl
     * @return mixed
     */
    public function set($key, $value, $ttl = 0) {
        $key = $this->prefix . $key;
        switch ($this->cacheType) {
            case "shmcache":
                if (empty($ttl)) {
                    return $this->shmCache->set($key, $value);
                } else {
                    return $this->shmCache->set($key, $value, $ttl);
                }
                break;
            default:
                $this->lastError = "cache type not exist";
                return false;
        }
    }

    /**
     * 功能描述：获取缓存内容
     * @param $key
     * @return mixed
     */
    public function get($key) {
        $key = $this->prefix . $key;
        switch ($this->cacheType) {
            case "shmcache":
                return $this->shmCache->get($key);
                break;
            default:
                $this->lastError = "cache type not exist";
                return false;
        }
    }

    /**
     * 功能描述：自增
     * @param $key
     * @param $num
     * @param $ttl
     * @return mixed
     */
    public function incr($key, $num,$ttl=864000000) {
        $key = $this->prefix . $key;
        switch ($this->cacheType) {
            case "shmcache":
                return $this->shmCache->incr($key,$num,$ttl);
                break;
            default:
                $this->lastError = "cache type not exist";
                return false;
        }
    }

    /**
     * 功能描述：删除key
     * @param $key
     * @return mixed
     */
    public function del($key) {
        $key = $this->prefix . $key;
        switch ($this->cacheType) {
            case "shmcache":
                return $this->shmCache->delete($key);
                break;
            default:
                $this->lastError = "cache type not exist or not support del commend";
                return false;
        }
    }

    /**
     * 功能描述：获取最近一次错误的信息
     * @return mixed
     */
    public function getLastError() {
        return $this->lastError;
    }
}

